package com.sky.happygos.ui.activity;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.widget.EditText;
import android.widget.Toast;

import com.sky.happygos.R;
import com.sky.happygos.base.BaseA;
import com.sky.happygos.common.LoadView;
import com.sky.happygos.event.LoginE;

import com.sky.happygos.model.Token;
import com.sky.happygos.network.TokenPrefs_;
import com.sky.happygos.present.UserP;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * Created by qqqqqqq on 2017/4/14.
 */
@EActivity(R.layout.activity_login)
public class LoginA extends BaseA{

    public static final String EXECT_CHECK_TOKEN = "EXECT_CHECK_TOKEN";

    @Bean
    UserP userP;

    @ViewById(R.id.et_login_phone)
    EditText phoneE;
    @ViewById(R.id.et_login_pw)
    EditText passwrodE;
    @ViewById(R.id.loadView)
    LoadView loadView;

    @Extra(EXECT_CHECK_TOKEN)
    String checkToken;


    @Pref
    TokenPrefs_ tokenPrefs;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if(!"NO".equals(checkToken)) {
            if (tokenPrefs.token().get() != null) {
                MainA_.intent(this).start();
                finish();
            }
        }else{
            tokenPrefs.edit().token().remove().apply();
            tokenPrefs.edit().userid().remove().apply();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Click(R.id.login)
    public void login(){
        String phoneStr = phoneE.getText().toString();
        try {
            long phone = Long.parseLong(phoneStr);
            String pwStr = passwrodE.getText().toString();
            loadView.start();
            userP.login(phone,pwStr);
        }catch (NumberFormatException e){
            Toast.makeText(this,"手机号码错误，或存在非法字符",Toast.LENGTH_SHORT).show();
        }

    }

    @Click(R.id.header_right)
    public void register(){
        RegisterA_.intent(this).start();
    }

    @Subscribe
    public void loginResult(LoginE e){
        loadView.dismiss();
        if(e.isSuccess){
            MainA_.intent(this).start();
        }else{
            Toast.makeText(this,"登录失败:"+e.error.message,Toast.LENGTH_SHORT).show();
        }

    }



}
